<template>
  <!-- 添加滚动容器 -->
  <div class="scroll-container">
    <!-- 书籍列表 -->
    <div class="reading-page">
      <el-card
        v-for="book in books"
        :key="book.bookId"
        @click="$router.push(`/home/reading/book/${book.bookId}`)"
        class="book-card"
      >
        <img :src="book.cover" class="cover" />
        <div class="title">{{ book.title }}</div>
      </el-card>
    </div>

    <!-- 加载更多按钮 -->
    <div class="load-more-wrapper">
      <el-button
        v-if="hasMore"
        type="default"
        :loading="loading"
        @click="loadMore"
        class="load-more-btn"
      >
        {{ loading ? '加载中...' : '点击加载更多' }}
      </el-button>
      <div v-else class="no-more">没有更多书籍了</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getAllBooks } from '@/apis/book'

const books = ref([])
const page = ref(1)
const pageSize = ref(4) // 每页10条
const hasMore = ref(true)
const loading = ref(false)
const loadMoreRef = ref(null) // 加载更多元素引用

// 获取书籍数据
const fetchBooks = async () => {
  try {
    loading.value = true
    const response = await getAllBooks({
      pageNum: page.value,
      pageSize: pageSize.value,
    })

    // 合并新旧数据
    books.value = [...books.value, ...(response.data || [])]

    // 判断是否有更多数据
    hasMore.value = response.data?.length === pageSize.value
  } catch (error) {
    console.error('Failed to fetch books:', error)
  } finally {
    loading.value = false
  }
}

// 初始加载
onMounted(fetchBooks)

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    page.value++
    fetchBooks()
  }
}
</script>

<style scoped>
/* 滚动容器 */
.scroll-container {
  display: flex;
  flex-direction: column;
}

.reading-page {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 16px;
  padding: 16px;
  overflow-y: auto; /* 启用垂直滚动 */
}

.load-more-wrapper {
  padding: 20px;
  text-align: center;
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.load-more-btn {
  width: 200px;
  background-color: #f5f5f5; /* 灰白背景 */
  color: #555; /* 深灰文字 */
  border: 1px solid #ccc; /* 浅灰边框 */
}

.load-more-btn:hover {
  background-color: #e0e0e0; /* 鼠标悬浮时更深一点的灰 */
  border-color: #bbb;
  color: #333;
}
.book-card {
  width: 160px;
  cursor: pointer;
  transition: transform 0.2s;
}

.book-card:hover {
  transform: translateY(-4px);
}

.cover {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.title {
  margin-top: 8px;
  text-align: center;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
